/*
 * Copyright 2007 Agile Plugins Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * 	http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.googlecode.agileplugins.cruisewatcher;

import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

public class CruiseBuildWatcher {
    private String lastDate = null;

    private boolean lastFailed = false;
    private final CruiseBuild cruiseBuild;
    private final CruiseWatcherSettings settings;
    private BuildDialogPresenter buildDialogPresenter;

    public CruiseBuildWatcher(CruiseBuild cruiseBuild, CruiseWatcherSettings settings) {
        this.cruiseBuild = cruiseBuild;
        this.settings = settings;
        buildDialogPresenter = new BuildDialogPresenter(cruiseBuild, settings);
    }

    public void watch() throws IOException {
        String rssfeed = downloadFeed();
        FeedParser feedParser = new MasterFeedParser();
        LatestBuildState latestBuildState = feedParser.parseLatestBuildResult(cruiseBuild, rssfeed);
        if (!latestBuildState.wasAt(lastDate)) {
            lastDate = latestBuildState.getDate();
            if (latestBuildState.wasFailure()) {
                buildDialogPresenter.showImageDialog(true, "The " + cruiseBuild.getName() + " Build Is Broken", "Ok, I'll Fix It");
                lastFailed = true;
            } else if (lastFailed) {
                buildDialogPresenter.showImageDialog(false, "The " + cruiseBuild.getName() + " Build Is Fixed", "OK");
                lastFailed = false;
            }
        }
    }

    private String downloadFeed() throws IOException {
        URL url = new URL(settings.baseUrl + cruiseBuild.getRssUrl());
        InputStream inputStream = url.openStream();
        return IOUtils.toString(inputStream);
    }
}
